var form_a ,layer
/**
 * 视图渲染
 * @Param where 渲染位置
 * @Param templateName 模板名
 * @Param data 渲染数据
 * */
function viewToTemplate(where,templateName,data) {
    var html = $('script[type="text/'+templateName+'"]').html();//模板代码
    var arr=[];
    $("#"+where).html("");//清空tbody
    $.each(data, function (index, object) {
        arr.push(formatTemplate(object, html));
    });
    $("#"+where).append(arr.join(""));
}
function formatTemplate(object, tmpl,fun) {
    //m1 匹配到的字符{W} m2 字符的内容 W
    return tmpl.replace(/{(\w+)}/g,function (m1, m2) {
        if(!m2){
            return "";
        }
        if (typeof fun == 'function' ){
            fun();
        }
        return object[m2];
    })
}
function makePage(result){
    $("#page_Info").empty();
    var center=$("<center></center>").append("当前第"+result.pageNum+"页,总共"+result.pages+
        " 页,总"+result.total+" 条数记录");
    $("#page_Info").append(center);

}
function build_page_nav(result,categoryId,title){
    $("#page_nav").empty();
    var ul=$("<ul></ul>").addClass("pagination");
    var firstPage=$("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
    var prePage=$("<li></li>").append($("<a></a>").append("&laquo;").attr("href","#"));
    if(result.hasPreviousPage==false){
        firstPage.addClass("disabled");
        prePage.addClass("disabled");
    }else{
        //为元素添加点击事件
        firstPage.click(function(){
            to_Page(1,categoryId,title);
        });
        prePage.click(function(){
            to_Page(result.pageNum-1,categoryId,title);
        });
    }


    var nextPage=$("<li></li>").append($("<a></a>").append("&raquo;").attr("href","#"));
    var lastPage=$("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
    if(result.hasNextPage==false){
        nextPage.addClass("disabled");
        lastPage.addClass("disabled");
    }else{
        lastPage.click(function(){
            to_Page(result.pages,categoryId,title);
        });
        nextPage.click(function(){
            to_Page(result.pageNum+1,categoryId,title);
        });
    }


    ul.append(firstPage).append(prePage);
    $.each(result.navigatepageNums,function(index,item){
        var num=$("<li></li>").append($("<a></a>").append(item).attr("href","#"));
        if(result.pageNum==item){
            num.addClass("active");
        }
        num.click(function(){
            to_Page(item,categoryId,title);
        });
        ul.append(num);
    });
    ul.append(nextPage).append(lastPage);
    var nav=$("<nav></nav>").addClass("Page navigation").append(ul);
    nav.appendTo("#page_nav");
}
/**
 * 分页跳转
 * @param pn 跳转页数
 */
function to_Page(pn, categoryId,title){
    var data;
    if(categoryId === null || categoryId === undefined ){
        if(title === null || title === undefined) {
            data = {"pn":pn};
        }else {
            data ={"pn":pn,"title":title};
        }

    }else if(title === null || title === undefined){
        data = {"pn":pn, "categoryId":categoryId};
    }else{
        data = {"pn":pn, "categoryId":categoryId,"title":title};
    }
    $.ajax({
        url:"/product/getProduct",
        data:data,
        type:"post",
        success:function(res){
            viewToPage("product_table_list","product_table_list",res,categoryId);
        }
    })
}
/**
 * 分页+视图渲染
 * @param id 渲染位置
 * @param templateName 模板名称
 * @param data 数据渲染
 * @param title
 */
function viewToPage(id, templateName, data,categoryId,title){
    var res = data.extend.productList;
    priceAdopt(res.list);
    dataParseUrl(res.list)
    viewToTemplate(id,templateName,dataParse(res.list))
    makePage(res,categoryId,title);
    build_page_nav(res,categoryId,title);
}

/**
 * 价格处理
 * @param data
 * @returns {*}
 */
function priceAdopt(data) {
    for (var i=0;i <data.length; i++){
        data[i].price /= 100;
    }
    return data;
}

/**
 * 数据状态处理
 * @param data
 * @returns {*}
 */
function dataParse(data) {
    for(var i=0; i<data.length; i++){
        data[i].status = data[i].status == '0' ? '否':'是';
    }
    return data;
}

/**
 * 数据图片处理
 * @param data
 * @returns {*}
 */
function dataParseUrl(data) {
    for(var i=0; i<data.length; i++) {
        if ((data[i].image).match(new RegExp("^/local/image.*$"))){
            // data[i].image = "http://localhost:8080/upload/"+data[i].image.substr(6);
            data[i].image = '<img src="'+data[i].image.substr(6)+'" width="20" height="20" onmouseenter="imgBig(this)" onmouseleave="imgSmall(this)"/>'
        }else {
            data[i].image = '<img src="https://images.weserv.nl/?url='+data[i].image+'" width="20" height="20" onmouseenter="imgBig(this)" onmouseleave="imgSmall(this)"/>'
        }
    }
    return data;
}

/**
 * 设置商品的状态
 * @param id
 * @param status
 */
function setProductStatus(id,status) {
    $.ajax({
        url:"/product/setProductStatus",
        type:'post',
        data:{"id":id,"status":status},
        success:function (res) {
            if(res.code == '200'){

                var data = [];
                data[0] = res.extend.product[0];
                data = dataParse(data);
                data = priceAdopt(data);
                data = dataParseUrl(data);
                viewToTemplate("table_list_"+id,"product_tr_list",data)
            }else {
                alert("操作失败 ")
            }
        }
    })
}
//--------------------------------------------------------------
/**
 * 根据不同条件获取商品
 * @param categoryId
 * @param title
 */
function getProducts(categoryId,title) {
    var data;
    if (categoryId === null) {
        if(title === null){
            data = null;
        }else {
            data = {"title":title}
        }
    }else if(title === null){
        data = {"categoryId":categoryId};
    }else{
        data = {"categoryId":categoryId,"title":title};
    }

    $.ajax({
        url:"/product/getProduct",
        type:"post",
        data:data,
        success:function (res) {
            viewToPage("product_table_list","product_table_list",res,categoryId,title);
        }
    })
//    上架
}function rayons(id){
    setProductStatus(id,1)
}
//下架
function un(id){
    setProductStatus(id,0)
}

/**
 * 根据id删除商品
 * @param id
 */
function delProductById(id){
    sweetAlert({
        title:"是否删除",
        text:"你将无法更改!",
        type:"warning",
        showCancelButton:true,
        confirmButtonColor:"#dd6b55",
        closeOnConfirm:true
    },function (isConfired) {
        if(isConfired){
            $.ajax({
                url:"/product/delProductById",
                type:"post",
                data:{"id":id},
                success:function (data) {
                    if(data.code == "200"){
                        sweetAlert("删除","商品已删除","success")
                        $("#table_list_"+id).empty();
                    }else {
                        sweetAlert("失败",data.msg,"error");
                    }

                }
            })
        }
    })
}

/**
 * 搜索
 */
function searchProductByTitle(){
    var title = $("#product_search").val();
    getProducts(null,title);
}
layui.use(['upload','form','layer'], function() {
    var form = layui.form;
    var upload = layui.upload;
    var laye = layui.layer;
    layer = laye;
    form_a =form;
    //监听提交
    form.render();
    //拖拽上传

    //fisrt select 改变事件
    form.on('select(provid)',function () {
        var id = $("#select_first :selected").val();

        getChildCategory(id);
    })
    //second select 改变事件
    form.on('select(cityid)',function () {
        var id = $("#select_second :selected").val();
        getProducts(id,null)
    })


});
function checkAllSelection() {

}
/**
 * 一级分类获取
 */
function getParentCategory(){

    $.ajax({
        url:"/category/queryCategories",
        type:"post",
        data:{"isParent":1},
        success:function (res) {
            if(res.code == "200 ") {
                renderFirstSelection(res.extend.list,res.extend.list.length)
            }else {

            }
        }
    })
}

/**
 * 二级分类获取
 */
function getChildCategory(id){
    $.ajax({
        url:"/category/queryCategories",
        type:"post",
        data:{"parentId":id,"isParent":0},
        success:function (res) {
            if(res.code == "200") {
                renderSecondSelection(res.extend.list)
            }else {

            }
        }
    })

}

/**
 * 渲染一级分类
 * @param data
 */
function renderFirstSelection(data){
    var fisrt = $('#select_first');
    fisrt.html("")
    fisrt.append("<option value=\"0\">一级分类</option>")
    for(var i=0; i<data.length; i++) {
        fisrt.append('<option value="'+(data[i].id)+'">'+data[i].name+'</option>')
    }
    // form_a.render('select')
}

/**
 * 渲染二级分类
 * @param data
 */
function renderSecondSelection(data){
    var fisrt = $('#select_second');
    fisrt.html("")
    fisrt.append("<option value=\"0\">二级分类</option>")
    for(var i=0; i<data.length; i++) {
        fisrt.append('<option value="'+(data[i].id)+'">'+data[i].name+'</option>')
    }
    form_a.render('select')
}

/**
 * 批量操作
 */
function getChecked(){
    var ids =[];
    $("input:checkbox").each(function (i) {
        if(this.checked){
            ids[i]=this.value;
        }
    })
    return  ids;
}
function rayonsChecked(){
   var data = getChecked();
   if(data.length <=0) {

   }else {
      for (var i=0; i<data.length;i++){
          setProductStatus(data[i],1);
      }
   }
}
function unChecked(){
    var data = getChecked()
    if(data.length <=0) {

    }else {
        for (var i=0; i<data.length;i++){
            setProductStatus(data[i],0);
        }
    }
}
function delProductByIds(){
    var data = getChecked()
    if(data.length <=0) {
    }else {
        for (var i=0; i<data.length;i++){
            delProductById(data[i]);
        }
    }
}

/**
* 通过分类id或者产品id查询产品
* @param categoryId
* @param id
*/
function getProudctsByCondiction(categoryId,id){
    var data={};
    if(categoryId !== undefined || categoryId !== null) {
        data.categoryId = categoryId;
    }
    if (id !== undefined || id !== null) {
        data.id = id;
    }
    $.ajax({
        url:"/product/getProductById",
        type:"post",
        data:data,
        success:function (result) {
            modal_view(result);
        }
    })
}
/**
 * 修改商品
 * @param id
 */
function updateProduct(id){
    getProudctsByCondiction(null,id)
}

/**
 * modal 渲染
 */
function modal_view(data){
    data = data.extend.product;
    $("#modal_image").attr("src",data.image);
    $("#modal_title").val(data.title);
    $("#modal_price").val("价格：￥"+data.price/100);
    $("#modal_id").val(data.id);
    $("#modal_num").val(data.num);
    $("#modal_status").val(data.status)
    $("#exampleModal").modal('show')
}
//加载后事件
$(document).ready(function () {
    //获取一级分类
    getParentCategory();
    //获取所有产品
    getProducts(null,null);
    //check添加事件
    $("#checkout_all").on("click",function () {
        $("input:checkbox").prop("checked","checked");
    });
    $("#checkNo").on("click",function () {
        $("input:checkbox").removeAttr("checked")
    })
    $("#checkRev").on("click",function () {
        $("input:checkbox").each(function () {
            this.checked =!this.checked;
        })
    })
    $("#exampleModal").on('hide.bs.modal',function () {
        $("#modal_image").attr("src","");
        $("#modal_title").val("")
        $("#modal_price").val("");
        $("#modal_id").val("");
        $("#modal_num").val("")
        $("#modal_status").val("")
    });
    //提交事件
    $("#submit").click(function () {
        //简单校验一下省份等信息
        var id = $("#modal_id").val();
        var status = $("#modal_status").val();
        var jsonData ={};
        jsonData.image = $("#modal_image").attr("src");
        jsonData.title = $("#modal_title").val();
        jsonData.price = parseInt($("#modal_price").val().substr(4))*100;
        jsonData.num = $("#modal_num").val();
        jsonData.id = id;
        console.log(jsonData)
        $.ajax({
            url:"/product/updateProduct",
            type:"post",
            data: jsonData,
            success:function (data) {
                $("#exampleModal").modal("hide");
                if(data.code == "200"){
                    setProductStatus(id,status);
                }else{
                    alert(data.msg)
                }

            }
        })
    });
})